package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @description: 根据uid获得作者昵称
 * @author: chengbaiyi
 * @create: 2022-05-24 20:36
 */
@WebServlet("/getauthor")
public class GetAuthorServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知错误！";
        UserInfo userInfo = new UserInfo();
        String uidStr = req.getParameter("uid");
        if (!StrUtil.isBlank(uidStr)) {
            int uid = Integer.parseInt(uidStr);
            // 从数据库中查询作者昵称
            Connection connection = DBUtils.getConnection();
            String sql = "select nickname from userinfo where uid=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, uid);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                userInfo.setNickname(resultSet.getString("nickname"));
            }
            msg = "";
        } else {
            msg = "不存在该作者！";
        }
        // 将数据返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200, userInfo, msg)));
    }
}
